<template>
  <div class="admin-container">
    <div class="page-header">
      <h2>管理员管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加管理员
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入用户名"
            clearable
          />
        </el-col>
        <el-col :span="8">
          <el-select v-model="searchForm.role" placeholder="选择角色" clearable>
            <el-option label="全部角色" value="" />
            <el-option label="普通管理员" value="1" />
            <el-option label="超级管理员" value="2" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 管理员表格 -->
    <div class="admin-table">
      <el-table
        :data="adminList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="username" label="用户名" min-width="200" />
        <el-table-column prop="roleDisplay" label="角色" min-width="150">
          <template #default="{ row }">
            <el-tag
              :type="getRoleTagType(row.role)"
              size="small"
            >
              {{ row.roleDisplay }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="300">
          <template #default="{ row }">
            <span class="text-gray-500">管理员账户</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :disabled="isCurrentUser(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 管理员添加/编辑对话框 -->
    <AdminDialog
      v-model:visible="dialogVisible"
      :admin-data="currentAdmin"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Download,
  Search
} from '@element-plus/icons-vue'
import { getAdminsApi, deleteAdminApi } from '@/api/admin/admin'
import AdminDialog from './components/AdminDialog.vue'

const userStore = useUserStore()

// 当前用户
const currentUser = computed(() => userStore.userInfo)

// 响应式数据
const loading = ref(false)
const adminList = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  role: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentAdmin = ref({})

// 数据获取方法
const loadAdmins = async () => {
  try {
    loading.value = true

    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 添加搜索条件
    if (searchForm.search) {
      params.search = searchForm.search
    }

    // 添加角色过滤
    if (searchForm.role) {
      params.role = searchForm.role
    }

    const response = await getAdminsApi(params)

    if (response.code === 200) {
      adminList.value = response.data.data || []
      total.value = response.data.totalCount || 0
      ElMessage.success(`查询到 ${adminList.value.length} 条管理员记录`)
    } else {
      ElMessage.error(response.message || '获取管理员列表失败')
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 方法
const handleSearch = () => {
  currentPage.value = 1  // 重置到第一页
  loadAdmins()
}

const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    role: ''
  })
  currentPage.value = 1
  loadAdmins()
}

const handleAdd = () => {
  isEdit.value = false
  currentAdmin.value = {}
  dialogVisible.value = true
}

const handleExport = () => {
  ElMessage.info('导出数据功能开发中...')
}

const handleEdit = (row) => {
  isEdit.value = true
  currentAdmin.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除管理员 ${row.username} 吗？删除后将无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteAdminApi(row.id)

    if (response.code === 200) {
      ElMessage.success(response.message || '删除成功')
      // 重新加载数据
      loadAdmins()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除管理员失败:', error)
      ElMessage.error('删除管理员失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1  // 重置到第一页
  loadAdmins()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadAdmins()
}

const handleDialogSuccess = () => {
  // 重新加载数据
  loadAdmins()
}

// 工具方法
const getRoleTagType = (role) => {
  switch (role) {
    case 'SUPER_ADMIN':
      return 'danger'
    case 'ADMIN':
      return 'primary'
    default:
      return 'info'
  }
}

const isCurrentUser = (row) => {
  return row.id === currentUser.value?.id
}

onMounted(() => {
  loadAdmins()
})
</script>

<style lang="scss" scoped>
.admin-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }
  
  .admin-table {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;

    .el-table {
      width: 100%;
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .admin-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
      
      .header-actions {
        width: 100%;
        justify-content: flex-start;
      }
    }
    
    .search-section {
      .el-col {
        margin-bottom: 15px;
      }
    }
  }
}
</style>
